/*
 * Galaxium Messenger
 * 
 * Copyright (C) 2008 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Globalization;
using System.Net;
using System.Xml;

using Anculus.Core;

using Galaxium.Core;

namespace Galaxium.Protocol.Msn
{
	public class MsnClientConfig
	{
		public delegate void EnsureConfigDelegate ();
		delegate void DownloadDelegate ();
		
		const string _url = "http://config.messenger.msn.com/Config/MsgrConfig.asmx";
		
		string _args;
		XmlElement _configRoot;
		
		public XmlElement ConfigRoot
		{
			get { return _configRoot; }
		}
			
		public MsnClientConfig ()
		{
			//TODO: is TwoLetterISORegionName the correct value?
			// What's PLCID for?
			
			RegionInfo regionInfo = RegionInfo.CurrentRegion;
			if (regionInfo == null)
				regionInfo = new RegionInfo ("US");
			
			_args = string.Format ("?op=GetClientConfig&Country={0}&CLCID={1:x4}&PLCID={2:x4}",
			                       regionInfo.TwoLetterISORegionName, // For now, to protect against issues.
			                       CultureInfo.CurrentCulture.LCID,
			                       0);
			
			//Log.Debug (_args);
			
			RequestConfig (delegate { });
		}
		
		void RequestConfig (EnsureConfigDelegate callback)
		{
			Log.Debug ("Requesting client config from {0}", _url + _args);
			
			//TODO: WebClient.DownloadStringAsync doesn't work in mono 1.2.4
			// Use DownloadStringAsync when 1.2.4 is no longer used
			
			DownloadDelegate d = delegate
			{
				WebClient client = new WebClient ();
				
				try
				{
					string data = client.DownloadString (_url + _args);
					
					ThreadUtility.SyncDispatch (new VoidDelegate (delegate
					{
						ProcessConfig (data);
						
						if (callback != null)
							callback ();
					}));
				}
				catch (Exception ex)
				{
					Log.Warn (ex, "Error downloading or parsing client config");
					_configRoot = null;
				}
			};
			
			if (callback != null)
				d.BeginInvoke (null, null);
			else
				d.Invoke ();
		}
		
		void ProcessConfig (string data)
		{
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (data);
			
			_configRoot = doc.DocumentElement;
			ThrowUtility.ThrowIfFalse ("Invalid client config", _configRoot.LocalName == "MsgrConfig");
			
			Log.Debug ("Client config loaded");
		}
		
		public void EnsureConfig (EnsureConfigDelegate callback)
		{
			if (_configRoot != null)
			{
				if (callback != null)
					callback ();

				return;
			}
			
			RequestConfig (callback);
		}
	}
}
